#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-01-26 12:14:21

import threading
import gevent
import queue
import argparse
import sys
import subprocess
import datetime

q = queue.Queue()


class MyThread(threading.Thread):
    """docstring for  """

    def __init__(self, queue):
        super(MyThread, self).__init__()
        self.q = queue
        self.all_cor = []

    def getCommand(self, item):
        platform, serverid, ip = item.strip().split(',')
        action_dict = {
            'df': 'df -h',
            'sleep': 'sleep 1',
            'ls': 'ls -l'
        }
        platform, qufu_id, ip, command = item.strip().split(',')
        if command == 'sleep' or command == 'ls':
            cmd = action_dict[command]
        else:
            cmd = ''' ssh root@%s -n "%s"''' % (ip, action_dict[command])
        return cmd

    def run_command(self, cmd):
        with open('/data/wangtest.log', 'a+') as logfile:
            exit_code = subprocess.call(cmd, shell=True, stdout=logfile, stderr=subprocess.STDOUT)
        # print('%s 执行结果为 %s' % (cmd, exit_code))

    def run(self):
        while True:
            item = self.q.get()
            cmd = self.getCommand(item)
            # self.run_command(cmd)
            self.all_cor.append(gevent.spawn(self.run_command, cmd))
            # gevent.spawn(self.run_command, cmd)
            # print('完成')

            if self.q.empty() or len(self.all_cor) >= 100:
                print('开始join协程')
                gevent.joinall(self.all_cor)
                print(len(self.all_cor))
                # self.all_cor = []
            self.q.task_done()


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', dest='file_list', action='store', help='区服列表文件')
    parser.add_argument('-v', dest='version', action='store', help='版本')
    parser.add_argument('-a', dest='action', action='store', help='执行动作')

    action_list = [
        'df',
        'sleep',
        'ls',
    ]

    version_list = [
        'test',
        '37dev',
        '37stable'
    ]

    usage = '''
        -f 区服列表  -v 版本 -a 执行操作
    '''

    opt = parser.parse_args()
    if opt.action not in action_list:
        print('%s 是不支持的操作' % opt.action)
        sys.exit(1)

    if opt.listfile is None or opt.version not in version_list:
        print(usage)
        sys.exit(1)
    else:
        with open('/script/WinAndLinux/coroutine/%s' % opt.listfile, 'r') as f:
            content = f.readlines()

    if len(content) <= 200:
        maxlen = int(len(content) / 5)
    else:
        maxlen = int(200 / 100)

    for t in range(maxlen):
        t = MyThread(q)
        t.setDaemon(True)
        t.start()

    print('start:%s' % datetime.datetime.now().strftime('%H:%M:%S'))
    for i in content:
        info = i.strip().split(',')
        item = '%s,%s,%s,%s' % (info[0], info[1], info[2], opt.action.strip())
        q.put(item)
    q.join()

    '''
    print(len(all_cor))
    gevent.joinall(all_cor)
    '''

    print('end:%s' % datetime.datetime.now().strftime('%H:%M:%S'))
